<?php

namespace yiike\goods\backend\controllers;

use yiike\goods\model\GoodsCategory;
//use yiike\goods\model\Region;
use yiike\goods\model\GoodsSearch;
use dmstr\bootstrap\Tabs;
use yii\helpers\Url;
use yiike\goods\model\Goods;
use yiike\goods\model\GoodsSpec;
use common\models\Region;
use yiike\store\model\Store;

/**
 * This is the class for controller "GoodsController".
 */
class GoodsController extends \yiike\goods\backend\controllers\base\GoodsController
{
    //所有的商品管理
    public function actionIndex()
    {
        $searchModel = new GoodsSearch;
        $dataProvider = $searchModel->search($_GET);

        Tabs::clearLocalStorage();

        Url::remember();
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
    //某个商家下的商品管理
    public function actionStoreGoods($store_id)
    {

        $store = Store::findOne(['id'=>$store_id]);

        $_GET['GoodsSearch']['store_id'] = $store_id;
        $searchModel = new GoodsSearch;
        $dataProvider = $searchModel->search($_GET);

        Tabs::clearLocalStorage();

        Url::remember();
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->render('storeGoods', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'store'=>$store,
        ]);
    }
    public function actionCreate($store_id)
    {

        $store = Store::findOne(['id'=>$store_id]);
        $model = new Goods;
        $model->store_id = $store_id;
        $category = GoodsCategory::find()->select('id,name,parent_id')->where(['parent_id' => 0, 'status' => 1])->asArray()->all();

        $cate = GoodsCategory::find()->select('id,name,parent_id')->where(['<>', 'parent_id', 0])->andWhere(['status' => 1])->asArray()->all();

        $provinces = Region::find()->select('id,name,parent_id')->where(['parent_id' => 0])->asArray()->all();
        $provincesHtml = '';
        foreach ($provinces as $k => $v) {
            $provincesHtml .= <<<eof
        <div style='float: left;position: relative;width: 170px;height: 35px;line-height: 35px;border: 1px solid #fff;'>
            <label class="checkbox-inline" style="margin-left:20px;">
                   <input type="checkbox" class="cityall" style="margin-top:12px;" value="{$v['name']}"> {$v['name']}                         <span class="citycount" style="color:#ff6600"></span>
             </label>
         </div>
eof;

        }

        foreach ($category as $k => $v) {
            $arr[$v['id']] = $v['name'];
        }
        foreach ($arr as $k => $v) {
            foreach ($cate as $m => $n) {
                if ($n['parent_id'] == $k) {
                    $arr[$v][$n['id']] = $n['name'];
                }
            }
        }
        $category = $arr;
        $tags = ['1' => '推荐', '2' => '新品', '3' => '热卖', '4' => '包邮'];
        $is_spec = 0;
        $spec_data = [];
        $property = [];
        try {
            if ($model->load($_POST)) {
                $province = $_POST['Goods']['province'];
                $province = Region::getCityName($province);
                $city = $_POST['Goods']['city'];
                $city = Region::getCityName($city);
                $model->location_p = $province;
                $model->location_c = $city;
                if ($model->save()) {
                    if (!empty($_POST['is_spec']) &&  $_POST['is_spec']== '1') {
                        if (count($_POST['spec_name']) >= 1) {
                            for ($i = 0; $i < count($_POST['spec_name']); $i++) {
                                $spec_data[] = [
                                    $model->id,
                                    $_POST['spec_name'][$i],
                                    '',
                                    $_POST['spec_price'][$i],
                                    $_POST['spec_orig_price'][$i],
                                    $_POST['spec_cost_price'][$i],
                                    $_POST['spec_stock'][$i],
                                    $_POST['spec_goods_sn'][$i],
                                    $_POST['spec_weight'][$i]
                                ];

                            }
                        }
                    }

                    $spec_field = ['goods_id', 'name', 'image', 'price', 'orig_price', 'cost_price', 'stock', 'goods_sn', 'weight'];
                    \Yii::$app->db->createCommand()->batchInsert('ims_ttyc_goods_spec', $spec_field, $spec_data)->execute();
                }


                return $this->redirect(['index', 'id' => $model->id,'store_id'=>$store_id]);
            } elseif (!\Yii::$app->request->isPost) {
                $model->load($_GET);
            }
        } catch (\Exception $e) {
            $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
            $model->addError('_exception', $msg);
        }
        return $this->render('create', [
            'model' => $model, 'category' => $category,
            'provincesHtml' => $provincesHtml,
            'is_spec' => $is_spec,
            'SpecData' => $spec_data,
            'property' => $property,
            'tags'=>$tags,
            'store'=>$store
        ]);
    }

    public function actionUpdate($id,$store_id)
    {

        $store = Store::findOne(['id'=>$store_id]);

        $cateModel = new GoodsCategory();
        $category = $cateModel->find()->select('id,name,parent_id')->where(['parent_id' => 0, 'status' => 1])->asArray()->all();
        $cate = $cateModel->find()->select('id,name,parent_id')->where(['<>', 'parent_id', 0])->andWhere(['status' => 1])->asArray()->all();
        $regionModel = new Region();
        $provinces = $regionModel->find()->select('id,name,parent_id')->where(['parent_id' => 0])->asArray()->all();
        $SpecModel = new GoodsSpec();
        $SpecData = $SpecModel->find()->select('*')->where(['goods_id' => $id])->asArray()->all();

        $provincesHtml = '';
        foreach ($provinces as $k => $v) {
            $provincesHtml .= <<<eof
        <div style='float: left;position: relative;width: 170px;height: 35px;line-height: 35px;border: 1px solid #fff;'>
            <label class="checkbox-inline" style="margin-left:20px;">
                   <input type="checkbox" class="cityall" style="margin-top:12px;" value="{$v['name']}"> {$v['name']}                         <span class="citycount" style="color:#ff6600"></span>
             </label>
         </div>
eof;

        }

        foreach ($category as $k => $v) {
            $arr[$v['id']] = $v['name'];
        }
        foreach ($arr as $k => $v) {
            foreach ($cate as $m => $n) {
                if ($n['parent_id'] == $k) {
                    $arr[$v][$n['id']] = $n['name'];
                }
            }
        }
        $category = $arr;
        $model = $this->findModel($id);
        $model->province = Region::getCityId($model->location_p);
        $model->city = Region::getCity($model->location_c, $model->province);
        $property = json_decode($model->property, true);
        $is_spec = $model->is_spec;
        $tags = ['1' => '推荐', '2' => '新品', '3' => '热卖', '4' => '包邮'];
        if ($model->load($_POST)) {
            $province = $_POST['Goods']['province'];
            $province = Region::getCityName($province);
            $city = $_POST['Goods']['city'];
            $city = Region::getCityName($city);
            $model->location_p = $province;
            $model->location_c = $city;


            if ($model->save()) {

                if ($model->is_spec == 1) {

                    if (count($_POST['spec_name']) >= 1) {
                        for ($i = 0; $i < count($_POST['spec_name']); $i++) {
                            if (!empty($_POST['spec_id'][$i])) {
                                $spec = $SpecModel::findOne($_POST['spec_id'][$i]);
                                $spec->name = $_POST['spec_name'][$i];
                                $spec->image = '';
                                $spec->price = $_POST['spec_price'][$i];
                                $spec->orig_price = $_POST['spec_orig_price'][$i];
                                $spec->cost_price = $_POST['spec_cost_price'][$i];
                                $spec->goods_sn = $_POST['spec_goods_sn'][$i];
                                $spec->weight = $_POST['spec_weight'][$i];
                                $res = $spec->save();
                            } else {
                                $spec_data[] = [
                                    $model->id,
                                    $_POST['spec_name'][$i],
                                    '',
                                    //  $_POST['spec_img'][$i] ,
                                    $_POST['spec_price'][$i],
                                    $_POST['spec_orig_price'][$i],
                                    $_POST['spec_cost_price'][$i],
                                    $_POST['spec_stock'][$i],
                                    $_POST['spec_goods_sn'][$i],
                                    $_POST['spec_weight'][$i]
                                ];

                                $spec_field = ['goods_id', 'name', 'image', 'price', 'orig_price', 'cost_price', 'stock', 'goods_sn', 'weight'];

                            }
                        }
                        if (!empty($spec_data)) {
                            \Yii::$app->db->createCommand()->batchInsert('ims_ttyc_goods_spec', $spec_field, $spec_data)->execute();
                        }
                    }
                } else {
                    $SpecModel::deleteAll(['goods_id' => $id]);
                }
                return $this->redirect(Url::toRoute(['store-goods','store_id'=>$store_id]));
            }else{
                return $this->render('update', [
                    'model' => $model,
                    'category' => $category,
                    'provincesHtml' => $provincesHtml,
                    'is_spec' => $is_spec,
                    'SpecData' => $SpecData,
                    'property' => $property,
                    'tags'=>$tags,
                    'store'=>$store,
                    'store_id'=>$store_id
                ]);
            }

        } else {
            return $this->render('update', [
                'model' => $model,
                'category' => $category,
                'provincesHtml' => $provincesHtml,
                'is_spec' => $is_spec,
                'SpecData' => $SpecData,
                'property' => $property,
                'tags'=>$tags,
                'store'=>$store,
            ]);
        }
    }

    public function actionSpecDel($id)
    {
        try {
            $SpecModel = new GoodsSpec();
            $res = $SpecModel::find()->where(['id' => $id])->one();
            $res = $res->delete();
            if ($res) {
                return true;
            }

        } catch (\Exception $e) {
            $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
            \Yii::$app->getSession()->addFlash('error', $msg);
            return $this->redirect(Url::previous());
        }
    }
    public function actionDelete($id)
    {
        try {
            $this->findModel($id)->delete();
        } catch (\Exception $e) {
            $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
            \Yii::$app->getSession()->addFlash('error', $msg);
            return $this->redirect(Url::previous());
        }

// TODO: improve detection
        $isPivot = strstr('$id', ',');
        if ($isPivot == true) {
            return $this->redirect(Url::previous());
        } elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') {
            Url::remember(null);
            $url = \Yii::$app->session['__crudReturnUrl'];
            \Yii::$app->session['__crudReturnUrl'] = null;

            return $this->redirect($url);
        } else {
            return $this->redirect(['index']);
        }
    }
    //省市县三级
    public function actions()
    {
        $actions = parent::actions();
        $actions['get-region'] = [
            'class' => \chenkby\region\RegionAction::className(),
            'model' => \common\models\Region::className()
        ];
        $actions['upload'] =  [
            'class' => 'kucha\ueditor\UEditorAction',
        ];
        return $actions;
    }

}
